package com.fansl.allround.common.core.util;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * @author fansl
 * @Description: 二维码生成工具
 * @date 2020/2/3 10:43
 */
public class ZXingUtil {
    public static void encodeImg(String imgPath,String format,String content,int width,int height,String logo) throws Exception{
        Hashtable<EncodeHintType,Object> hints = new Hashtable<>();
        //排错率 L<M<Q<H
        hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);
        //编码
        hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
        //外边距：margin
        hints.put(EncodeHintType.MARGIN,1);
        /**
         * content :需要加密的文字
         * BarCodeFormat.QR_CODE:需要解析类型（二维码）
         * hints:加密涉及的一些参数：编码，排错率
         */
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE,width,height,hints);
        //内存中的一张推片：此时需要的图片是二维码->需要一个Boolean[][]->BitMatrix
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        for (int x =0;x<width;x++){
            for (int y=0;y<height;y++){
                image.setRGB(x,y,(bitMatrix.get(x,y)? Color.BLACK.getRGB():Color.WHITE.getRGB()));
            }
        }
        //画logo
        image = LogoUtil.logoMatrix(image,logo);
        //string->file
        File file = new File(imgPath);
        //生成图片
        ImageIO.write(image,format,file);
    }

    public static void decodeImg(File file)throws Exception{
        if (!file.exists()){
            return;
        }
        //file->内存中的一张图片
        BufferedImage image = ImageIO.read(file);
        MultiFormatReader formatReader = new MultiFormatReader();
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
        //图片->result
        Map map =new HashMap<EncodeHintType,String>(1);
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");
        Result result = formatReader.decode(binaryBitmap,map);
        System.out.println("解析结果："+result.toString());
    }

    public static void main(String[] args) {
         String imgPath = "src/二维码.png";
         String content = "hello world";
         String logo = "src/logo.png";
        try {
            ZXingUtil.encodeImg(imgPath,"png",content,430,430,logo);
            ZXingUtil.decodeImg(new File(imgPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
